package com.thp.bigdata.inverIndex;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 到排索引第一步
 * @author 汤小萌
 *
 */
public class InverIndexStepOne {
	
	static class InverIndexStepOneMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
		Text k = new Text();
		IntWritable v = new IntWritable(1);
		@Override
		protected void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			String[] words = line.split("\t");
			FileSplit inputSplit = (FileSplit) context.getInputSplit();
			String fileName = inputSplit.getPath().getName();
			for(String word : words) {
				k.set(word + "--" + fileName);
				context.write(k, v);
			}
		}
	}
	
	static class InverIndexStepTwoReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
			int count = 0;
			for(IntWritable value : values) {
				count += value.get();
			}
			context.write(key, new IntWritable(count));
		}
	}
	
	/**
	 *  hello--a.txt	3
		hello--b.txt	2
		hello--c.txt	2
		jerry--a.txt	1
		jerry--b.txt	3
		jerry--c.txt	1
		tom--a.txt	2
		tom--b.txt	1
		tom--c.txt	1
	 * @param args
	 * @throws IOException
	 * @throws ClassNotFoundException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		job.setJarByClass(InverIndexStepOne.class);
		
		job.setMapperClass(InverIndexStepOneMapper.class);
		job.setReducerClass(InverIndexStepTwoReducer.class);
		
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		FileInputFormat.setInputPaths(job, new Path("F:/inverIndex/input"));
		FileOutputFormat.setOutputPath(job, new Path("F:/inverIndex/output_1"));
		
		System.exit(job.waitForCompletion(true) ? 0 : 1);
		
		
		
	}
	
}
